package Team.Yaohuo.task;


import Team.Yaohuo.config.ThreadLocalConfig;
import Team.Yaohuo.constant.JDYConstant;
//import Team.Yaohuo.listener.RabbitListenerWait;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpMethod;
import org.springframework.http.ResponseEntity;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;
import org.springframework.web.client.RestTemplate;

import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 简道云定时请求代办数据
 */
@Component
@Slf4j
public class JdyMessageGetTask {

    @Autowired
    private RabbitTemplate rabbitTemplate;
    @Autowired
    private HttpServletRequest httpServletRequest;
    @Autowired
    private RestTemplate restTemplate;

    private Integer count = 0;

    @Scheduled(cron = "0/5 * * * * ? ")
    /**
     * 每5秒请求代办 判断是否与给定的count相同 如果相同 放置消息队列中
     */
    public void setTimeToRabbitListenerWait() {
        String userId = ThreadLocalConfig.getCurrentId();

        if (userId == null || userId.equals("")) {
            return;
        }
        // 获取当前用户的简道云消息待办
        Map<String, Object> jdyMapWait = new HashMap<>();
        jdyMapWait.put("username", userId);
        HttpHeaders httpHeaders = new HttpHeaders();
        httpHeaders.add("Authorization", "Bearer " + JDYConstant.API_KEY);
        HttpEntity<Object> httpEntity = new HttpEntity<>(jdyMapWait, httpHeaders);
        ResponseEntity<Map> waitMessage = restTemplate.exchange(JDYConstant.PENDING_TASKS_IN_JIANDAOYUN, HttpMethod.POST, httpEntity, Map.class);
        List<Map> tasks = (List) waitMessage.getBody().get("tasks");
        log.info("当前有：{}条代办", tasks.size());

        if (count != tasks.size()) {
            rabbitTemplate.convertAndSend("", "messageQueue", tasks);
            count = tasks.size();
        }
    }
}
